﻿using System;

namespace Library.Util
{
    public class ImageUtil : FileUtil
    {
        public static void Resize(string originalFile, string newFile, int newWidth, int maxHeight)
        {
            System.Drawing.Image fullSizeImage = System.Drawing.Image.FromFile(originalFile);

            // Prevent using images internal thumbnail
            fullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            fullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            
            int newHeight = fullSizeImage.Height * newWidth / fullSizeImage.Width;
            if (newHeight > maxHeight)
            {
                // Resize with height instead
                newWidth = fullSizeImage.Width * maxHeight / fullSizeImage.Height;
                newHeight = maxHeight;
            }

            System.Drawing.Image newImage = fullSizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            fullSizeImage.Dispose();

            // Save resized picture
            newImage.Save(newFile);
        }
    }
}